package com.mall.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mall.exception.MyException;
import com.mall.model.CommClass;
import com.mall.model.Commodity;
import com.mall.model.User;
import com.mall.service.CommClassService;
import com.mall.service.CommodityService;
import com.mall.util.MyUtil;
import com.mall.util.RedisUtil;
import com.mall.util.SerializeUtil;
import com.mall.util.ValidGroup2;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Controller
@RequestMapping("/commodity")
public class CommodityController extends MyUtil {

	@Autowired
	private CommodityService commodityService;
	@Autowired
	private CommClassService commClassservice;
	/**
	 * 商城首页
	 * 
	 * @dagewang 2017年8月29日
	 */
	@RequestMapping("/index")
	public String index(Model model, HttpSession session, String type, Integer page) throws Exception {
		if (page == null || page.equals("")) {
			page = 0;
		}
		model.addAttribute("page", page);
		List<Commodity> list = commodityService.indexList(type, page);
		if (list.size() == 0) {
			model.addAttribute("list", null);
		} else {
			model.addAttribute("list", list);
		}
		/**
		 * 如果排序类型不为空
		 */
		if (type != null) {
			model.addAttribute("type", type);
		}
		return "index";
	}
	/**
	 * 首次进入,从redis数据库读取首页数据
	 *
	 *@dagewang 2017年10月23日
	 */
	@RequestMapping("/redisIndex")
	public String redisIndex(Model model){
		JedisPool jedis = RedisUtil.getJedis();
		Jedis r = jedis.getResource();
		byte[] bs = r.get("commoditys".getBytes());
	Commodity[] unserialize =(Commodity[]) SerializeUtil.unserialize(bs);
		RedisUtil.close(jedis, r);
		model.addAttribute("list", unserialize);
			return "index";
		
	}

	/**
	 * 筛选
	 * 
	 * @dagewang 2017年8月30日
	 */
	@RequestMapping("/screen")
	public String screen(Integer page, String meidi, String changhong, String geli, String haier, String ximenzi,
			String qita, Model model, Double sprice, Double eprice, HttpSession session, String categoryid)
					throws Exception {
		if (page == null || page.equals("")) {
			page = 0;
		}
		model.addAttribute("page", page);
		List<Commodity> list = commodityService.screen(meidi, changhong, geli, haier, ximenzi, qita, sprice, eprice,
				categoryid, page);
		if (list.size() == 0) {
			model.addAttribute("list", null);
		} else {
			model.addAttribute("list", list);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ximenzi", ximenzi);
		map.put("changhong", changhong);
		map.put("geli", geli);
		map.put("meidi", meidi);
		map.put("haier", haier);
		map.put("qita", qita);
		map.put("ximenzi", ximenzi);
		map.put("sprice", sprice);
		map.put("eprice", eprice);
		map.put("categoryid", categoryid);
		model.addAttribute("map", map);
		return "index";
	}

	/**
	 * 获取单个商品全部信息
	 *
	 * @dagewang 2017年8月29日
	 */
	@RequestMapping("getComm")
	public String getComm(Model model, Integer id) throws Exception {
		List<Object> list = commodityService.get(id);

		if (list.get(0) == null || list.get(1) == null) {
			throw new MyException("该商品不存在");
		}
		List<CommClass> byCommId = commClassservice.getByCommId(id);
		model.addAttribute("comm", list.get(0));
		model.addAttribute("commD", list.get(1));
		model.addAttribute("classlist", byCommId);
		return "commodityDetailed";
	}

	/**
	 * 更新商品简单信息
	 *
	 * @dagewang 2017年8月22日
	 */
	@RequestMapping("/updateComm")
	public @ResponseBody Map<String, Object> updateComm(@Validated(value = { ValidGroup2.class }) Commodity comm,
			BindingResult b) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 判空,b为注解校验的返回值
		if (b.hasErrors()) {
			map.put("result", null);
			return map;
		}
		boolean update = commodityService.update(comm);
		if (!update) {
			map.put("result", null);
		}
		map.put("result", "1");
		return map;

	}

	/**
	 * 客户搜索商品
	 * 
	 * @dagewang 2017年8月21日
	 */
	@RequestMapping("/search")
	public String search(String keyword, String sort, Model model, Integer page, Double snum, Double ednum)
			throws Exception {
		model.addAttribute("keyword", keyword);
		if (page == null || page.equals("")) {
			page = 0;
		}
		model.addAttribute("page", page);
		if (this.isNull(keyword, sort)) {
			return "search";
		} else {
			List<Commodity> search = commodityService.search(keyword, sort, page, snum, ednum);
			if (search.size() > 0) {
				model.addAttribute("commlist", search);
			}
		}
		model.addAttribute("sort", sort);
		model.addAttribute("snum", snum);
		model.addAttribute("ednum", ednum);
		return "search";
	}

	/**
	 * 后台管理搜索商品
	 *
	 * @dagewang 2017年8月21日
	 */
	@RequestMapping("/searchComm")
	public String searchComm(String search, Model model, Integer page, Integer bs) throws Exception {
		if (search == null || search.equals("") || bs == null || bs.equals("")) {
			throw new MyException("出现了内部错误");
		}
		if (page == null) {
			page = 0;
		}
		model.addAttribute("page", page);
		List<Commodity> list = commodityService.search(search, page);
		if (list.size() == 0) {
			model.addAttribute("commodity", null);
		} else {
			model.addAttribute("commodity", list);
		}
		if (bs == 3) {
			return "commodityShelves";
		}
		if (bs == 4) {
			return "commodityAll";
		}
		if (bs == 5) {
			return "sysCommKill";
		}
		return "commodityDelete";

	}

	/**
	 * 首页按照大类获取商品集合
	 *
	 * @dagewang 2017年8月21日
	 */
	@RequestMapping("/searchCommIndex")
	public String searchCommIndex(String categoryid, Model model, Integer page, String type) throws Exception {
		if (categoryid == null || categoryid.equals("")) {
			throw new MyException("出现了内部错误");
		}
		if (page == null) {
			page = 0;
		}
		model.addAttribute("page", page);
		List<Commodity> list = commodityService.search(categoryid, page, type);
		if (list.size() == 0) {
			model.addAttribute("list", null);
		} else {
			model.addAttribute("list", list);
		}
		if (type != null && !type.equals("")) {
			model.addAttribute("type", type);
		}
		model.addAttribute("categoryid", categoryid);
		return "index";

	}

	/**
	 * 商品集合
	 *
	 * @dagewang 2017年8月21日
	 */
	@RequestMapping("/listCommodity")
	public String listCommodity(Model model, Integer page) throws Exception {
		if (page == null) {
			page = 0;
		}
		model.addAttribute("page", page);
		List<Commodity> list = commodityService.list(page, null);
		if (list.size() == 0) {
			model.addAttribute("commodity", null);
		} else {
			model.addAttribute("commodity", list);
		}
		return "commodityDelete";
	}

	/**
	 * 商品上下架集合
	 *
	 * @dagewang 2017年8月21日
	 */
	@RequestMapping("/listShelves")
	public String listShelves(Model model, Integer page, Integer shelves) throws Exception {
		if (page == null) {
			page = 0;
		}
		model.addAttribute("page", page);
		List<Commodity> list = commodityService.list(page, shelves);
		if (list.size() == 0) {
			model.addAttribute("commodity", null);
		} else {
			model.addAttribute("commodity", list);
		}
		model.addAttribute("shelves", shelves);
		return "commodityShelves";
	}

	/**
	 * 所有商品
	 *
	 * @dagewang 2017年8月21日
	 */
	@RequestMapping("/listAll")
	public String listAll(Model model, Integer page, String kill) throws Exception {
		if (page == null) {
			page = 0;
		}
		model.addAttribute("page", page);
		List<Commodity> list = commodityService.list(page, null);
		if (list.size() == 0) {
			model.addAttribute("commodity", null);
			model.addAttribute("pageNum", 0);
		} else {
			model.addAttribute("commodity", list);
			Integer pageNum = commodityService.pageNum();
			model.addAttribute("pageNum", pageNum);
		}
		if (kill != null && !kill.equals("")) {
			return "sysCommKill";
		}
		return "commodityAll";
	}

	/**
	 * 更新商品上下架状态
	 *
	 * @dagewang 2017年8月22日
	 */
	@RequestMapping("/updateShelves")
	public @ResponseBody Map<String, Object> updateShelves(Integer id, Integer shelves) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		boolean result = commodityService.update(id, shelves);
		if (result) {
			map.put("result", 1);
		} else {
			map.put("result", null);
		}
		return map;
	}

	/**
	 * 添加商品
	 * 
	 * @dagewang 2017年8月12日
	 */
	@RequestMapping("/addCommodity")
	public @ResponseBody Map<String, Object> addCommodity(Commodity comm, Model model) throws Exception {
		MyUtil m = new MyUtil();
		if (m.isNull(comm.getBrand(), comm.getCategoryid(), comm.getParameter(), comm.getPrice(), comm.getTitle(),
				comm.getStock(), comm.getTitleimg())) {
			throw new MyException("所有项目为必填项,请不要留空");
		}
		Commodity commodity = commodityService.saveCommodity(comm);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("commid", commodity.getId());
		return map;
	}

	/**
	 * 删除指定商品
	 *
	 * @dagewang 2017年8月21日
	 */
	@RequestMapping("/deleteComm")
	public void deleteComm(Integer id) throws Exception {
		if (id == null || id.equals("")) {
			throw new MyException("出现了错误");
		}
		commodityService.deleteImg(id);
	}

	/**
	 * 上传图片 MultipartFile为文件参数,接收name要和页面一致
	 * 
	 * @dagewang 2017年8月1日
	 */
	@RequestMapping("/uploadImg")
	public @ResponseBody Map<String, Object> uplodImg(MultipartFile img, HttpServletRequest httpServletRequest,
			Integer commid, Integer num) throws Exception {
		String newimg = null;
		if (img != null) {
			newimg = commodityService.uploadImg(img, httpServletRequest, commid, num);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("img", newimg);
		return map;

	}

	/**
	 * 上传多张图片
	 *
	 * @dagewang 2017年8月14日
	 */
	@RequestMapping("/uploadImgs")
	public @ResponseBody Map<String, Object> uplodImgs(MultipartFile img0, MultipartFile img1, MultipartFile img2,
			MultipartFile img3, HttpServletRequest httpServletRequest, Integer id) throws Exception {
		List<MultipartFile> list = new ArrayList<MultipartFile>();
		list.add(img0);
		list.add(img1);
		list.add(img2);
		list.add(img3);
		Map<String, Object> map = new HashMap<String, Object>();
		for (int i = 0; i < 4; i++) {
			if (list.get(i) != null) {
				map.put("img" + i, commodityService.uploadImgD(list.get(i), httpServletRequest));
			}
		}
		return map;

	}

	/**
	 * 上传多张图片
	 *
	 * @dagewang 2017年8月14日
	 */
	@RequestMapping("/uploadImgsTo")
	public @ResponseBody Map<String, Object> uplodImgs(MultipartFile img0, MultipartFile img1, MultipartFile img2,
			MultipartFile img3, HttpServletRequest httpServletRequest) throws Exception {
		List<MultipartFile> list = new ArrayList<MultipartFile>();
		list.add(img0);
		list.add(img1);
		list.add(img2);
		list.add(img3);
		Map<String, Object> map = new HashMap<String, Object>();
		for (int i = 0; i < 4; i++) {
			if (list.get(i) != null) {
				map.put("img" + i, commodityService.uploadImgTo(list.get(i), httpServletRequest));
			}
		}
		return map;

	}

	/**
	 * @RequestBody把接收到的数据转换成key,value形式
	 * @ResponseBody把返回的数据转换成Json格式
	 * @dagewang 2017年8月2日
	 */
	@RequestMapping("/updateCommodity")
	public @ResponseBody User updateCommodity(@RequestBody User user, Model m) throws Exception {
		return user;
	}

	@RequestMapping("/deleteImg")
	public void deleteImg(String imgName, HttpServletRequest httpServletRequest) throws Exception {
		commodityService.deleteImg(imgName, httpServletRequest);
	}

	public CommodityService getCommodityService() {
		return commodityService;
	}

	public void setCommodityService(CommodityService commodityService) {
		this.commodityService = commodityService;
	}

	public CommClassService getCommClassservice() {
		return commClassservice;
	}

	public void setCommClassservice(CommClassService commClassservice) {
		this.commClassservice = commClassservice;
	}

}
